﻿#include "plan_manager_quadrant_widget.h"
#include "ui_plan_manager_quadrant_widget.h"
#include "plan_list_item_widget.h"
#include "global_manager.h"
#include <QDateTime>
#include <QUuid>
#include <QFile>
#include "easylogging++.h"
#include "plan_list_item_widget.h"
#include "sqlite_manager.h"

PlanManagerQuadrantWidget::PlanManagerQuadrantWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PlanManagerQuadrantWidget),
    m_timer(new QTimer),
    m_itemMenu(new QMenu),
    m_currentMenuOfItem(nullptr)
{
    ui->setupUi(this);
    this->initUI();
    this->initMenu();
    this->initEvents();
}

PlanManagerQuadrantWidget::~PlanManagerQuadrantWidget()
{
    delete ui;
}

void PlanManagerQuadrantWidget::setQuadrantName(const QString quadrantName)
{
    ui->titleLabel->setText(quadrantName);
    initData(quadrantName);
}

void PlanManagerQuadrantWidget::initUI()
{
    // 定制样式
#ifdef Q_OS_ANDROID
    QFile styleFile(":/resources/qss/plan_manager_quadrant_widget_android.qss");
    styleFile.open(QIODevice::ReadOnly);
    QString stylesheet = styleFile.readAll();
    styleFile.close();
#else
    QFile styleFile(":/resources/qss/plan_manager_quadrant_widget.qss");
    styleFile.open(QIODevice::ReadOnly);
    QString stylesheet = styleFile.readAll();
    styleFile.close();
#endif

    setStyleSheet(stylesheet);
}

void PlanManagerQuadrantWidget::initEvents()
{
    m_timer->setInterval(1000);
    connect(ui->planOperatorWidget, &PlanOperatorWidget::addNewTriggered, this, [=]() {
        addNewPlanItemWidget("", "");
    });
}

void PlanManagerQuadrantWidget::initData(QString label)
{
    SqliteManager sm;
    QList<QVariantList> data;
    sm.selectData("plan_info", {"uuid", "name"}, {{"label", label}}, data);

    foreach (QVariantList row, data) {
        addNewPlanItemWidget(row[0].toString(), row[1].toString());
    }
}

void PlanManagerQuadrantWidget::initMenu()
{
    if (nullptr == m_itemMenu) {
        m_itemMenu = new QMenu;
    }

    QAction *deleteItem = new QAction(QString("删除"));
    m_itemMenu->addAction(deleteItem);

    connect(deleteItem, &QAction::triggered, this, &PlanManagerQuadrantWidget::onDeleteActionTriggered);
}

void PlanManagerQuadrantWidget::addNewPlanItemWidget(QString uuid, QString text)
{
    QListWidgetItem *item = new QListWidgetItem;
    item->setFlags(item->flags() & ~Qt::ItemIsSelectable);
    ui->planListWidget->addItem(item);

    PlanListItemWidget *itemWidget = new PlanListItemWidget;
    itemWidget->setUuid(uuid);
    itemWidget->setText(text);
    ui->planListWidget->setItemWidget(item, itemWidget);
    item->setSizeHint(QSize(0, itemWidget->size().height()));

    connect(itemWidget, &PlanListItemWidget::textChanged,
            this, &PlanManagerQuadrantWidget::onPlanListItemWidgetTextChanged);
    connect(itemWidget, &PlanListItemWidget::heightChanged, this, [=](int h) {
        item->setSizeHint(QSize(0, h));
    });
    connect(itemWidget, &PlanListItemWidget::menuTriggered, this, [=]() {
        m_currentMenuOfItem = item;
        m_itemMenu->exec(QCursor::pos());
    });
}

void PlanManagerQuadrantWidget::onPlanListItemWidgetTextChanged(PlanListItemWidget *itemWidget)
{
    QString uuid = itemWidget->getUuid();
    SqliteManager sm;

    if (uuid.isEmpty()) {
        uuid = QUuid::createUuid().toString(QUuid::WithoutBraces);
        LOG(DEBUG) << "create new uuid: " << uuid.toStdString();
        QList<QString> fields({"uuid", "name", "label"});
        QVariantList data({uuid, itemWidget->text(), ui->titleLabel->text()});
        bool ret = sm.insertRowData("plan_info", fields, data);
        if (ret)
        {
            itemWidget->setUuid(uuid);
        }
        else
        {
            LOG(ERROR) << "insert new data failed, error info: " << sm.lastError().toStdString();
        }
    }
    else {
        LOG(DEBUG) << "update plan text";
        QHash<QString, QVariant> data({{"name", itemWidget->text()}});
        QHash<QString, QVariant> whereCondition({{"uuid", uuid}});
        sm.updateData("plan_info", data, whereCondition);
    }
}

void PlanManagerQuadrantWidget::onDeleteActionTriggered()
{
    LOG(DEBUG) << "delete action triggered";
    if (nullptr == m_currentMenuOfItem) {
        LOG(ERROR) << "current menu of item is nullptr...";
        return ;
    }

    PlanListItemWidget* itemWidget =
            qobject_cast<PlanListItemWidget*>(ui->planListWidget->itemWidget(m_currentMenuOfItem));

    if (nullptr == itemWidget) {
        LOG(ERROR) << "current menu of item's widget is nullptr...";
        return ;
    }

    SqliteManager sm;

    QString uuid = itemWidget->getUuid();
    if (!uuid.isEmpty()) {
        sm.deleteData("plan_info", {{"uuid", itemWidget->getUuid()}});
    }

    delete ui->planListWidget->takeItem(ui->planListWidget->row(m_currentMenuOfItem));
}
